package br.gov.frameworkdemoiselle.security.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.owasp.esapi.ESAPI;
import org.owasp.esapi.User;

@WebListener
public class UserOnlineListener implements ServletContextListener {
	
	
	private long TIMEOUT = 1000 * 60 * 5;
	private long TIMEOUT_WITH_TOLERANCE = TIMEOUT + (1000*60);

	private static Map<String,Long> usersOnline = new HashMap <String,Long> ();
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// don't do anything
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		new TrendMonitoringThread().start();	//will get launched once
	}

	class TrendMonitoringThread extends Thread {
		public void run() {
			while (true) {
				
				for (String accountName : usersOnline.keySet()) {
					long userLastCheck = usersOnline.get(accountName);
					
					if ((userLastCheck - System.currentTimeMillis()) > TIMEOUT_WITH_TOLERANCE) {
						this.logoutUser (accountName);
					}
				}

				try {
					Thread.sleep(TIMEOUT); // run checks every 5 minutes
				} catch (InterruptedException e) {
					
				}
			}
		}
		public void logoutUser (String accountName) {
			usersOnline.remove(accountName);
			
			User user = ESAPI.authenticator().getUser(accountName);
			user.logout();
		}		
	}
	
	
	public static void refreshUser (String accountName) {		
		usersOnline.put(accountName, System.currentTimeMillis());
	}
}